﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using KXCXW.Web.Models;
using kxcxw.Data.Entities;
using kxcxw.Data.Common;
using kxcxw.Business;
using kxcxw.Data;
using System.Data.Entity.Validation;
using System.Data;

namespace KXCXW.Web.Controllers
{
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        KXCXWDBContext db = new KXCXWDBContext();
        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************  

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, AccountRepositories.GetMd5_16(model.Password)))
                {
                    SysUserInfo user = getUserByNameAndPwd(model.UserName, AccountRepositories.GetMd5_16(model.Password));
                    if (user.UserStatus == 1)
                    {
                        FormsService.SignIn(model.UserName, model.RememberMe);
                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "您的账号还没有激活请先到邮箱激活后再登录。");
                        ViewBag.ActiveError = "true";
                        ViewBag.User = user;
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名或密码不正确。");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        private SysUserInfo getUserByNameAndPwd(string username, string password)
        {
            try
            {
                SysUserInfo user = (from q in db.SysUserInfoes
                                    where q.UserName == username && q.UserPwd == password
                                    select q).FirstOrDefault();
                return user;

            }
            catch
            {
                return null;
            }
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/UserInfo
        // **************************************

        public ActionResult UserInfo()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            string userid = Membership.GetUser().ProviderUserKey.ToString();
            SysUserInfo userinfo = (from q in db.SysUserInfoes
                                    where q.UserID == userid
                                    select q).FirstOrDefault();
            ViewData["UserType"] = (from q in db.SysItemDetials
                                    where q.ItemDeitalID == userinfo.UserType
                                    select q).FirstOrDefault().itemDetialName;
            return View(userinfo);
        }

        [HttpPost]
        public ActionResult UserInfo(SysUserInfo model)
        {
            AccountRepositories accountserver = new AccountRepositories();
            SysUserInfo userinfo = db.SysUserInfoes.AsNoTracking().Single(x => x.UserID == model.UserID);
            if (userinfo.Email != model.Email && accountserver.ValidEmailAddressIsAlreadyExists(model.Email))
                ModelState.AddModelError("Email", "该邮箱已被占用！");
            if (ModelState.IsValid)
            {
                try
                {
                    db.Entry(model).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("SetUserInfoSuccess");
                }
                catch (DbEntityValidationException dbEx)
                {

                }
            }
            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        public ActionResult SetUserInfoSuccess()
        {
            return View();
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        //[HttpPost]
        //public ActionResult Register(RegisterModel model)
        //{
        //    AccountRepositories accountserver = new AccountRepositories();
        //    if (accountserver.ValidLoginNameIsAlreadyExists(model.UserName))
        //        ModelState.AddModelError("UserName", "该登录名已存在！");
        //    if (accountserver.ValidEmailAddressIsAlreadyExists(model.Email))
        //        ModelState.AddModelError("Email", "该邮箱已被注册！");
        //    if (ModelState.IsValid)
        //    {
        //        // Attempt to register the user
        //        model.UserStatus = 0;
        //        model.VerificationCode = Guid.NewGuid().ToString();
        //        MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.VerificationCode);

        //        if (createStatus == MembershipCreateStatus.Success)
        //        {
        //            new SendMailHelper().SendMail(model.Email, (Membership.GetUser(model.UserName).ProviderUserKey.ToString()), model.VerificationCode, model.UserName);
        //            FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
        //            return RedirectToAction("Index", "Home");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    ViewBag.PasswordLength = MembershipService.MinPasswordLength;
        //    return View(model);
        //}

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        #region 修改注册方式
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            string userID = "";
            AccountRepositories accountserver = new AccountRepositories();
            if (accountserver.ValidLoginNameIsAlreadyExists(model.UserName))
                ModelState.AddModelError("UserName", "该登录名已存在！");
            if (accountserver.ValidEmailAddressIsAlreadyExists(model.Email))
                ModelState.AddModelError("Email", "该邮箱已被注册！");
            if (ModelState.IsValid)
            {
                try
                {

                    // Attempt to register the user

                    SysUserInfo userinfo = new SysUserInfo();
                    userinfo.VerificationCode = Guid.NewGuid().ToString();

                    userinfo.UserType = "584745A6-F18F-4B54-B289-A7DF3DD2746C";//普通用户
                    userinfo.RegistrDate = DateTime.Now;
                    userinfo.UserID = Guid.NewGuid().ToString();
                    userinfo.UserName = model.UserName;
                    userinfo.UserPwd = AccountRepositories.GetMd5_16(model.Password);
                    userinfo.Email = model.Email;
                    userinfo.ConfirmPassword = AccountRepositories.GetMd5_16(model.ConfirmPassword);
                    userinfo.NickName = model.UserName;
                    //userinfo.UserStatus = DataConstants.Normal;
                    db.SysUserInfoes.Add(userinfo);
                    db.SaveChanges();
                    userID = userinfo.UserID;
                    SendMailHelper.SendMail(userinfo.Email, userinfo.UserID, userinfo.VerificationCode, userinfo.UserName);
                    string content = string.Format(@"恭喜大伙我们的网站又有一个叫{0}的新用户进驻了！他的邮箱是：{1}。状态：未激活。
                                我们先看看他/她什么时候激活吧！没过没有激活我们可以邮件通知她，看看有什么需要帮助的！
                                此邮件只发给开心促销网团队成员", model.UserName, model.Email);
                    SendMailHelper.SendEmailToOurWorker(content, "开心促销网新客户注册通知");
                    return RedirectToAction("RegisterSuccess/" + userID);
                }
                catch (DbEntityValidationException dbEx)
                {

                }
            }
            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }
        #endregion



        public ActionResult RegisterSuccess(string id)
        {
            SysUserInfo userInfo = db.SysUserInfoes.Find(id);
            return View(userInfo);
        }

        public ActionResult SendMail(string email, string userID, string verification, string userName)
        {
            string msg = SendMailHelper.SendMail(email, userID, verification, userName);
            if (msg == "true")
            {
                return RedirectToAction("SendEmailSuccess");
            }
            ViewBag.ErrorMessage = msg;
            return View();
        }
        public ActionResult SendEmailSuccess()
        {
            return View();
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, AccountRepositories.GetMd5_16(model.OldPassword), AccountRepositories.GetMd5_16(model.NewPassword)))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult Verification(string uid, string activeId)
        {
            SysUserInfo userInfo = db.SysUserInfoes.Where(q => q.UserID == uid && q.VerificationCode == activeId).FirstOrDefault();
            if (userInfo == null)
            {
                ViewData["VerficationMessage"] = "邮箱验证失败！";
                SendMailHelper.SendMail(new string[] { "qijinwen2005@qq.com" }, string.Format("客户:{0}，激活失败！", userInfo.UserName), "开心促销网开发人员通知");
            }
            else
            {
                try
                {
                    userInfo.UserStatus = 1;
                    userInfo.ConfirmPassword = userInfo.UserPwd;
                    db.Entry(userInfo).State = EntityState.Modified;
                    db.SaveChanges();
                    FormsService.SignIn(userInfo.UserName, false);
                    ViewData["VerficationMessage"] = "邮箱验证成功！";
                    string content = string.Format(@"恭喜大伙{0}的新用户已经激活了！
                                此邮件只发给开心促销网团队成员", userInfo.UserName);
                    SendMailHelper.SendEmailToOurWorker(content, "开心促销网新用户激活通知");
                }
                catch (DbEntityValidationException dbe)
                {

                }
            }
            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}
